using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using NeosSDI.Core.Attributes;


namespace NeosSDI.Core.Manager
{
    public class ModelMapperManager
    {
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public static void Initialize()
        {

            Assembly assembly = System.Web.Compilation.BuildManager.GetGlobalAsaxType().BaseType.Assembly;

            if (assembly != null)
            {
                foreach (var _type in assembly.GetTypes().Where(p => p.GetCustomAttributes(typeof(MapDtoAttribute), true).Count() > 0))
                {
                    MethodInfo methodInfo = _type.GetMethod("Map", System.Reflection.BindingFlags.Static | BindingFlags.NonPublic);
                    if (methodInfo == null)
                    {
                        AutoMapper.Mapper.CreateMap((_type.GetCustomAttributes(typeof(MapDtoAttribute), true)[0] as MapDtoAttribute).DtoType, _type);
                        AutoMapper.Mapper.CreateMap(_type, (_type.GetCustomAttributes(typeof(MapDtoAttribute), true)[0] as MapDtoAttribute).DtoType);
                    }
                    else
                    {
                        methodInfo.Invoke(null, new object[] { });
                    }
                }

            }
        }

        /// <summary>
        /// Initializes for unit test.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        public static void InitializeForUnitTest(Assembly assembly)
        {
            if (assembly != null)
            {
                foreach (var _type in assembly.GetTypes().Where(p => p.GetCustomAttributes(typeof(MapDtoAttribute), true).Count() > 0))
                {
                    MethodInfo methodInfo = _type.GetMethod("Map", System.Reflection.BindingFlags.Static | BindingFlags.NonPublic);
                    if (methodInfo == null)
                    {
                        AutoMapper.Mapper.CreateMap((_type.GetCustomAttributes(typeof(MapDtoAttribute), true)[0] as MapDtoAttribute).DtoType, _type);
                    }
                    else
                    {
                        methodInfo.Invoke(null, new object[] { });
                    }
                }

            }
        }
    }
}
